package com.xzit.controller;

import com.xzit.entity.User;
import com.xzit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(
            @RequestParam String username,
            @RequestParam String password,
            Model model) {
        
        // 检查是否被锁定
        String lockKey = "login_lock:" + username;
        if (redisTemplate.hasKey(lockKey)) {
            long lockTime = redisTemplate.getExpire(lockKey, TimeUnit.SECONDS);
            model.addAttribute("error", "账号已锁定，请 " + lockTime/60 + " 分钟后再试");
            return "login";
        }
        
        // 验证用户
        User user = userService.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            // 记录登录失败
            recordLoginFailure(username);
            
            // 获取失败次数
            String failKey = "login_fail:" + username;
            Integer failCount = (Integer) redisTemplate.opsForValue().get(failKey);
            if (failCount == null) {
                failCount = 0;
            }
            
            int remainingAttempts = 3 - failCount;
            if (remainingAttempts <= 0) {
                // 锁定账号30分钟
                redisTemplate.opsForValue().set(lockKey, "locked", 30, TimeUnit.MINUTES);
                model.addAttribute("error", "连续登录失败3次，账号已锁定30分钟");
            } else {
                model.addAttribute("error", "用户名或密码错误，剩余尝试次数: " + remainingAttempts);
            }
            return "login";
        }
        
        // 登录成功，清除失败记录
        clearLoginFailure(username);
        return "redirect:/channel/list";
    }

    private void recordLoginFailure(String username) {
        String failKey = "login_fail:" + username;
        Long failCount = redisTemplate.opsForValue().increment(failKey);
        
        // 如果是第一次失败，设置3分钟过期时间
        if (failCount != null && failCount == 1) {
            redisTemplate.expire(failKey, 3, TimeUnit.MINUTES);
        }
    }

    private void clearLoginFailure(String username) {
        String failKey = "login_fail:" + username;
        String lockKey = "login_lock:" + username;
        redisTemplate.delete(failKey);
        redisTemplate.delete(lockKey);
    }
}